package com.nantai.jiafang.nantaijiafang.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.nantai.jiafang.nantaijiafang.IConstant;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.activity.adapter.SearchDateAdapter;
import com.nantai.jiafang.nantaijiafang.utils.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class DataSearchActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_back;
    private int type = 1;
    private TextView tv_title;
    private TextView tv_state;
    private PopupWindow popupWindow;
    private PopupWindow popupWindow2;
    private ListView lv_group;
    private ListView lv_group2;
    private SearchDateAdapter adapter1;
    private SearchDateAdapter adapter2;
    private String[] numbers;
    private String[] numbers2;
    private Button btn_read;
    private Button btn_unread;
    private Button btn_open_close;
    private LinearLayout ll_search_conditions;
    private Button btn_search;
    private Context mContext;
    private TextView tv_search_item1;
    private TextView tv_search_item2;
    private TextView tv_search_item3;
    private EditText et_search1;
    private EditText et_search2;
    private EditText et_search3;
    private RelativeLayout rl_search3;
    private RelativeLayout rl_search2;
    private TextView tv_start_date;
    private TextView tv_end_date;
    private int current_start_end_date_state = 1;
    private ListView lv1;
    private ListView lv2;
    private LinearLayout ll_two_button;
    private Calendar calendar;
    private FrameLayout fl_list;
    private TextView tv_error_info;
    private ProgressDialog progressDialog;
    private int current_list = 1;
    private TextView tv_level;
    private String level = "";//面料等级 "":全部，A，B
    private String strs_level[] = new String[]{"全部", "A", "B"};
    private ScrollView sv_scroll;
    private LinearLayout ll_main1;
    private LinearLayout ll_main2;
    private JSONArray fabricBatchJson;
    private JSONArray fabricBatchJson2;
    private List listKey = new ArrayList<String>();
    private List listValue = new ArrayList<String>();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_search);
        mContext = DataSearchActivity.this;
        initViews();
        setup();
    }

    private void initViews() {
        tv_level = (TextView) findViewById(R.id.tv_level);
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("正在获取数据，请稍候");
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        ll_two_button = (LinearLayout) findViewById(R.id.ll_two_button);
        lv1 = (ListView) findViewById(R.id.lv1);
        lv2 = (ListView) findViewById(R.id.lv2);
        tv_error_info = (TextView) findViewById(R.id.tv_error_info);
        fl_list = (FrameLayout) findViewById(R.id.fl_list);
        tv_end_date = (TextView) findViewById(R.id.tv_end_date);
        tv_start_date = (TextView) findViewById(R.id.tv_start_date);
        tv_search_item1 = (TextView) findViewById(R.id.tv_search_item1);
        tv_search_item2 = (TextView) findViewById(R.id.tv_search_item2);
        tv_search_item3 = (TextView) findViewById(R.id.tv_search_item3);
        et_search1 = (EditText) findViewById(R.id.et_search1);
        et_search2 = (EditText) findViewById(R.id.et_search2);
        et_search3 = (EditText) findViewById(R.id.et_search3);
        rl_search3 = (RelativeLayout) findViewById(R.id.rl_search3);
        rl_search2 = (RelativeLayout) findViewById(R.id.rl_search2);
        btn_search = (Button) findViewById(R.id.btn_search);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_state = (TextView) findViewById(R.id.tv_state);
        btn_read = (Button) findViewById(R.id.btn_read);
        btn_unread = (Button) findViewById(R.id.btn_unread);
        btn_open_close = (Button) findViewById(R.id.btn_open_close);
        ll_search_conditions = (LinearLayout) findViewById(R.id.ll_search_conditions);
        sv_scroll = (ScrollView) findViewById(R.id.sv_scroll);
        ll_main1 = (LinearLayout) findViewById(R.id.ll_main1);
        ll_main2 = (LinearLayout) findViewById(R.id.ll_main2);
    }

    private void setup() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(calendar.getTime());
        tv_end_date.setText(date);
        calendar.add(Calendar.MONTH, -2);
        date = format.format(calendar.getTime());
        tv_start_date.setText(date);

        initTitle();
        tv_end_date.setOnClickListener(this);
        tv_start_date.setOnClickListener(this);
        tv_state.setOnClickListener(this);
        btn_read.setOnClickListener(this);
        btn_unread.setOnClickListener(this);
        tv_back.setOnClickListener(this);
        btn_open_close.setOnClickListener(this);
        ll_search_conditions.setOnClickListener(this);
        btn_search.setOnClickListener(this);
        tv_level.setOnClickListener(this);
    }

    private void initTitle() {
        type = getIntent().getIntExtra(IConstant.INTENT, 1);
        switch (type) {
            case IConstant.INTENT_PRODUCTION_ORDER_ATTITUDE:
                tv_title.setText("生产订单角度查询");
                tv_search_item1.setText("生产订单号");
                tv_search_item2.setText("面料编码/名称");
                btn_unread.setText("生产订单+等级");
                btn_read.setText("生产订单+面料+等级");
                rl_search3.setVisibility(View.GONE);
                break;
            case IConstant.INTENT_FabricBatch_ATTITUDE:
                tv_search_item1.setText("合同批号/批次号");
                tv_search_item2.setText("面料编码/名称");
                tv_search_item3.setText("供应商");
                btn_unread.setText("面料+等级");
                btn_read.setText("面料+供应商+等级");
                tv_title.setText("面料品种角度查询");
                break;
            case IConstant.INTENT_SUPPLIER_ATTITUDE:
                tv_search_item1.setText("合同批号/批次号");
                tv_search_item2.setText("面料编码/名称");
                tv_search_item3.setText("供应商");
                btn_unread.setText("供应商+面料+等级");
                btn_read.setText("供应商+采购合同号");
                tv_title.setText("供应商角度查询");
                break;
            case IConstant.INTENT_PRODUCTIONCOST_ATTITUDE:
                tv_search_item1.setText("");
                tv_title.setText("成品成本角度查询");
                tv_search_item1.setText("面料编码/名称");
                rl_search3.setVisibility(View.GONE);
                rl_search2.setVisibility(View.GONE);
                ll_two_button.setVisibility(View.GONE);
                break;
            case IConstant.INTENT_PURCHASECONTRACT_ACCITUDE:
                tv_search_item1.setText("合同批号/批次号");
                tv_search_item2.setText("面料编码/名称");
                tv_search_item3.setText("供应商");
                tv_title.setText("采购合同角度查询");
                ll_two_button.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_state:
                showPopWindow(tv_state);
                break;
            case R.id.btn_read:
                current_list = 2;
                btn_read.setTextColor(Color.BLUE);
                btn_unread.setTextColor(Color.BLACK);
                if(type == IConstant.INTENT_FabricBatch_ATTITUDE){
//                    ll_main1.removeAllViews();
//                    addView(fabricBatchJson2);
//                    progressDialog.dismiss();
                    sv_scroll.fullScroll(ScrollView.FOCUS_UP);
                    ll_main1.setVisibility(View.GONE);
                    ll_main2.setVisibility(View.VISIBLE);
                }else {
                    lv1.setVisibility(View.GONE);
                    lv2.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_unread:
                current_list = 1;
                btn_read.setTextColor(Color.BLACK);
                btn_unread.setTextColor(Color.RED);
                if(type == IConstant.INTENT_FabricBatch_ATTITUDE){
//                    progressDialog.show();
//                    ll_main1.removeAllViews();
//                    addView(fabricBatchJson);
//                    progressDialog.dismiss();
                    sv_scroll.fullScroll(ScrollView.FOCUS_UP);
                    ll_main1.setVisibility(View.VISIBLE);
                    ll_main2.setVisibility(View.GONE);
                }else {
                    lv1.setVisibility(View.VISIBLE);
                    lv2.setVisibility(View.GONE);
                }
                break;
            case R.id.btn_open_close:
                if (btn_open_close.getText().equals("收起")) {
                    btn_open_close.setText("展开");
                    ll_search_conditions.setVisibility(View.GONE);
                } else {
                    btn_open_close.setText("收起");
                    ll_search_conditions.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_search:
                if (Tools.isNetAvailuable(mContext)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date d1 = sdf.parse(tv_start_date.getText().toString());
                        Date d2 = sdf.parse(tv_end_date.getText().toString());
                        if (d1.after(d2)) {
                            Tools.showToast(mContext, "开始日期要在结束日期之后");
                        } else if (daysBetween(d1, d2) > 90) {
                            Tools.showToast(mContext, "日期间隔不能超过3个月");
                        } else {
                            progressDialog.show();
                            getDataFromNet();
                        }
                    } catch (ParseException e) {

                    }

                } else {
                    Tools.showToast(mContext, "当前网络不可用，请检查网络");
                }

                break;
            case R.id.tv_start_date:
                current_start_end_date_state = 1;
                DatePickerDialog dpd = new DatePickerDialog(mContext, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd.show();
                break;
            case R.id.tv_end_date:
                current_start_end_date_state = 2;
                DatePickerDialog dpd2 = new DatePickerDialog(mContext, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd2.show();
            case R.id.tv_level:
                showLevelDialog();
                break;
        }
    }

    private void showLevelDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("面料等级");
        builder.setItems(strs_level, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_level.setText(strs_level[which]);
                if (which == 0) {
                    level = "";
                } else {
                    level = strs_level[which];
                }
            }
        });
        builder.create().show();

    }


    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {

            if (current_start_end_date_state == 1) {
                tv_start_date.setText(myyear + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            } else {
                tv_end_date.setText(myyear + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }

        private void updateDate() {

        }
    };

    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    //调用接口
    private void getDataFromNet() {
        sv_scroll.setVisibility(View.GONE);
        fl_list.setVisibility(View.VISIBLE);
        switch (type) {
            case IConstant.INTENT_PRODUCTION_ORDER_ATTITUDE:
                getFromProductionOrderAttitude();
                break;
            case IConstant.INTENT_FabricBatch_ATTITUDE:
                getFromFabricBatchAttitude();
                break;
            case IConstant.INTENT_SUPPLIER_ATTITUDE:
                getFromSupplierAttitude();
                break;
            case IConstant.INTENT_PRODUCTIONCOST_ATTITUDE:
                getFromProductionCostAttitude();
                break;
            case IConstant.INTENT_PURCHASECONTRACT_ACCITUDE:
                getFromPurchaseContract();
                break;
        }

    }

    //从生产订单角度获取数据
    private void getFromProductionOrderAttitude() {
        RequestParams params = new RequestParams(IConstant.URL + "003012");
        //params.setSslSocketFactory(...); // 设置ssl
        params.addBodyParameter("txtDocNo", et_search1.getText().toString());
        params.addBodyParameter("txtComponentInvInfo", et_search2.getText().toString());
        params.addBodyParameter("txtBeginDate", tv_start_date.getText().toString());
        params.addBodyParameter("txtEndDate", tv_end_date.getText().toString());
        params.addBodyParameter("txtLevels", level);
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
                try {
                    JSONObject jo = new JSONObject(result);
                    JSONArray ja = jo.getJSONArray("list1");
                    JSONArray ja2 = jo.getJSONArray("list2");
                    if (ja != null && ja.length() > 0) {
                        fl_list.setVisibility(View.VISIBLE);
                        adapter1 = new SearchDateAdapter(mContext, ja, IConstant.INTENT_PRODUCTION_ORDER_ATTITUDE);
                        lv1.setAdapter(adapter1);
                        adapter2 = new SearchDateAdapter(mContext, ja2, IConstant.INTENT_PRODUCTION_ORDER_ATTITUDE);
                        adapter2.setIsList1(false);
                        lv2.setAdapter(adapter2);
                        if (current_list == 1) {
                            lv1.setVisibility(View.VISIBLE);
                            lv2.setVisibility(View.GONE);
                        } else {
                            lv1.setVisibility(View.GONE);
                            lv2.setVisibility(View.VISIBLE);
                        }
                        tv_error_info.setVisibility(View.GONE);
                    } else {
                        fl_list.setVisibility(View.GONE);
                        tv_error_info.setVisibility(View.VISIBLE);
                    }

                } catch (JSONException e) {
                    fl_list.setVisibility(View.GONE);
                    tv_error_info.setVisibility(View.VISIBLE);
                    tv_error_info.setText("数据解析出错");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                //Toast.makeText(mContext, ex.getMessage(), Toast.LENGTH_LONG).show();
                //System.out.println("出错：" + ex.getCause().toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });
    }

    //从采购合同角度获取数据
    private void getFromPurchaseContract() {
        RequestParams params = new RequestParams(IConstant.URL + "003011");
        //params.setSslSocketFactory(...); // 设置ssl
        params.addBodyParameter("txtcOrderCodeInfo", et_search1.getText().toString());
        params.addBodyParameter("txtComponentInvInfo", et_search2.getText().toString());
        params.addBodyParameter("txtcVenCode", et_search3.getText().toString());
        params.addBodyParameter("txtBeginDate", tv_start_date.getText().toString());
        params.addBodyParameter("txtEndDate", tv_end_date.getText().toString());
        params.addBodyParameter("txtLevels", level);
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
                try {
                    JSONObject jo = new JSONObject(result);
                    JSONArray ja = jo.getJSONArray("list1");
                    if (ja != null && ja.length() > 0) {
                        fl_list.setVisibility(View.VISIBLE);
                        adapter1 = new SearchDateAdapter(mContext, ja, IConstant.INTENT_PURCHASECONTRACT_ACCITUDE);
                        lv1.setAdapter(adapter1);
                        tv_error_info.setVisibility(View.GONE);
                    } else {
                        fl_list.setVisibility(View.GONE);
                        tv_error_info.setVisibility(View.VISIBLE);
                    }

                } catch (JSONException e) {
                    fl_list.setVisibility(View.GONE);
                    tv_error_info.setVisibility(View.VISIBLE);
                    tv_error_info.setText("数据解析出错");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                //Toast.makeText(mContext, ex.getMessage(), Toast.LENGTH_LONG).show();
                //System.out.println("出错：" + ex.getCause().toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });
    }

    //从面料品种角度获取数据
    private void getFromFabricBatchAttitude() {
        sv_scroll.setVisibility(View.VISIBLE);
        fl_list.setVisibility(View.GONE);
        ll_main1.removeAllViews();
        RequestParams params = new RequestParams( IConstant.URL + "003015");
        //params.setSslSocketFactory(...); // 设置ssl
        params.addBodyParameter("txtcOrderCodeInfo", et_search1.getText().toString());
        params.addBodyParameter("txtComponentInvInfo", et_search2.getText().toString());
        params.addBodyParameter("txtcVenCode", et_search3.getText().toString());
        params.addBodyParameter("txtBeginDate", tv_start_date.getText().toString());
        params.addBodyParameter("txtEndDate", tv_end_date.getText().toString());
        params.addBodyParameter("txtLevels", level);
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
//                System.out.println("返回结果：" + result);
                try {
                    JSONObject jo = new JSONObject(result);
                    JSONArray ja = jo.getJSONArray("list1");
                    JSONArray ja2 = jo.getJSONArray("list2");
                    if (ja != null && ja.length() > 0) {
//                        fl_list.setVisibility(View.VISIBLE);
//                        adapter1 = new SearchDateAdapter(mContext, ja, IConstant.INTENT_FabricBatch_ATTITUDE);
//                        lv1.setAdapter(adapter1);
//                        adapter2 = new SearchDateAdapter(mContext, ja2, IConstant.INTENT_FabricBatch_ATTITUDE);
//                        adapter2.setIsList1(false);
//                        lv2.setAdapter(adapter2);

                        fabricBatchJson = ja;
                        fabricBatchJson2 = ja2;
                        ll_main1.removeAllViews();
                        ll_main2.removeAllViews();
                        addView(ja);
                        addView2(ja2);
                        if (current_list == 1) {
                            ll_main1.setVisibility(View.VISIBLE);
                            ll_main2.setVisibility(View.GONE);

                            btn_read.setTextColor(Color.BLACK);
                            btn_unread.setTextColor(Color.RED);
                        } else {
                            ll_main1.setVisibility(View.GONE);
                            ll_main2.setVisibility(View.VISIBLE);

                            btn_read.setTextColor(Color.RED);
                            btn_unread.setTextColor(Color.BLACK);
                        }
                        progressDialog.dismiss();
                        tv_error_info.setVisibility(View.GONE);
                    } else {
                        fl_list.setVisibility(View.GONE);
                        sv_scroll.setVisibility(View.GONE);
                        tv_error_info.setVisibility(View.VISIBLE);
                    }

                } catch (JSONException e) {
                    fl_list.setVisibility(View.GONE);
                    sv_scroll.setVisibility(View.GONE);
                    tv_error_info.setVisibility(View.VISIBLE);
                    tv_error_info.setText("数据解析出错");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                //Toast.makeText(mContext, ex.getMessage(), Toast.LENGTH_LONG).show();
                //System.out.println("出错：" + ex.getCause().toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });
    }

    private  void addView(JSONArray ja){
        sv_scroll.fullScroll(ScrollView.FOCUS_UP);
        try {
            for(int i=0;i<ja.length();i++){
                listKey = new ArrayList<String>();
                listValue = new ArrayList<String>();
                ll_main1.addView(getBlankView(R.layout.item_divie_line));
                try {
                    JSONObject json = (JSONObject) ja.get(i);
                    Iterator it = json.keys();
                    while (it.hasNext()) {
                        String key = (String) it.next();
                        String value = json.getString(key);
                        if(key.contains("_")) {
                            listKey.add(key);
                            listValue.add(value);
                        }
//                        ll_main.addView(getItemView(key,value));
                    }
                    ll_main1.addView(getItemView("面料名称",json.getString("面料名称")));
                    ll_main1.addView(getItemView("面料编码",json.getString("面料编码")));
//                    if(current_list==2){
//                        for(int j = 1;j<=(listKey.size()/5);j++){
//                            ll_main1.addView(getItemView("供应商",json.getString("供应商_"+j)));
//                            ll_main1.addView(getItemView("等级",json.getString("等级_"+j)));
//                            ll_main1.addView(getItemView("裁剪用数",json.getString("裁剪用数_"+j)));
//                            ll_main1.addView(getItemView("领用米数",json.getString("领用米数_"+j)));
//                            ll_main1.addView(getItemView("综合利用率",json.getString("综合利用率_"+j)));
//                        }
////                    }else{
                        for(int j = 1;j<=(listKey.size()/4);j++){
                            ll_main1.addView(getItemView("等级",json.getString("等级_"+j)));
                            ll_main1.addView(getItemView("裁剪用数",json.getString("裁剪用数_"+j)));
                            ll_main1.addView(getItemView("领用米数",json.getString("领用米数_"+j)));
                            ll_main1.addView(getItemView("综合利用率",json.getString("综合利用率_"+j)));
                        }
//                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ll_main1.addView(getBlankView(R.layout.item_divie_blank));
            }
        } catch (Exception e) {

        }
    }

    private  void addView2(JSONArray ja){
        sv_scroll.fullScroll(ScrollView.FOCUS_UP);
        try {
            for(int i=0;i<ja.length();i++){
                listKey = new ArrayList<String>();
                listValue = new ArrayList<String>();
                ll_main2.addView(getBlankView(R.layout.item_divie_line));
                try {
                    JSONObject json = (JSONObject) ja.get(i);
                    Iterator it = json.keys();
                    while (it.hasNext()) {
                        String key = (String) it.next();
                        String value = json.getString(key);
                        if(key.contains("_")) {
                            listKey.add(key);
                            listValue.add(value);
                        }
//                        ll_main.addView(getItemView(key,value));
                    }
                    ll_main2.addView(getItemView("面料名称",json.getString("面料名称")));
                    ll_main2.addView(getItemView("面料编码",json.getString("面料编码")));
                        for(int j = 1;j<=(listKey.size()/5);j++){
                            ll_main2.addView(getItemView("供应商",json.getString("供应商_"+j)));
                            ll_main2.addView(getItemView("等级",json.getString("等级_"+j)));
                            ll_main2.addView(getItemView("裁剪用数",json.getString("裁剪用数_"+j)));
                            ll_main2.addView(getItemView("领用米数",json.getString("领用米数_"+j)));
                            ll_main2.addView(getItemView("综合利用率",json.getString("综合利用率_"+j)));
                        }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ll_main2.addView(getBlankView(R.layout.item_divie_blank));
            }
        } catch (Exception e) {

        }
    }

    private View getItemView(String str1,String str2){
        if(str1.contains("_")){
            str1 = str1.substring(0,str1.length()-2);
        }

        View view =LayoutInflater.from(this).inflate(R.layout.item_son_view,null);
        TextView name = (TextView) view.findViewById(R.id.tv_name);
        TextView content = (TextView) view.findViewById(R.id.tv_content);
        name.setText(str1);
        content.setText(str2);
        return view;
    }

    private View getBlankView(int resid){

        View view =LayoutInflater.from(this).inflate(resid,null);

        return view;
    }

    private View getItemView(JSONObject json){

        View view =LayoutInflater.from(this).inflate(R.layout.item_son_view,null);
        TextView name = (TextView) view.findViewById(R.id.tv_name);
        TextView content = (TextView) view.findViewById(R.id.tv_content);
        try {
            Iterator it = json.keys();
            while (it.hasNext()) {
                String key = (String) it.next();
                String value = json.getString(key);
                    name.setText(key);
                    content.setText(value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return view;
    }

    //从成品成本角度获取数据
    private void getFromProductionCostAttitude() {
        RequestParams params = new RequestParams(IConstant.URL + "003016");
        //params.setSslSocketFactory(...); // 设置ssl
        params.addBodyParameter("txtComponentInvInfo", et_search1.getText().toString());
        params.addBodyParameter("txtBeginDate", tv_start_date.getText().toString());
        params.addBodyParameter("txtEndDate", tv_end_date.getText().toString());
        params.addBodyParameter("txtLevels", level);
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
                try {
                    JSONObject jo = new JSONObject(result);
                    JSONArray ja = jo.getJSONArray("list1");
                    if (ja != null && ja.length() > 0) {
                        fl_list.setVisibility(View.VISIBLE);
                        adapter1 = new SearchDateAdapter(mContext, ja, IConstant.INTENT_PRODUCTIONCOST_ATTITUDE);
                        lv1.setAdapter(adapter1);
                        tv_error_info.setVisibility(View.GONE);
                    } else {
                        fl_list.setVisibility(View.GONE);
                        tv_error_info.setVisibility(View.VISIBLE);
                    }

                } catch (JSONException e) {
                    fl_list.setVisibility(View.GONE);
                    tv_error_info.setVisibility(View.VISIBLE);
                    tv_error_info.setText("数据解析出错");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                //Toast.makeText(mContext, ex.getMessage(), Toast.LENGTH_LONG).show();
                //System.out.println("出错：" + ex.getCause().toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });

    }

    //从供应商角度获取数据
    private void getFromSupplierAttitude() {
        RequestParams params = new RequestParams(IConstant.URL + "003010");
        //params.setSslSocketFactory(...); // 设置ssl
        params.addBodyParameter("txtcOrderCodeInfo", et_search1.getText().toString());
        params.addBodyParameter("txtComponentInvInfo", et_search2.getText().toString());
        params.addBodyParameter("txtcVenCode", et_search3.getText().toString());
        params.addBodyParameter("txtBeginDate", tv_start_date.getText().toString());
        params.addBodyParameter("txtEndDate", tv_end_date.getText().toString());
        params.addBodyParameter("txtLevels", level);
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
                try {
                    JSONObject jo = new JSONObject(result);
                    JSONArray ja = jo.getJSONArray("list1");
                    JSONArray ja2 = jo.getJSONArray("list2");
                    if (ja != null && ja.length() > 0) {
                        fl_list.setVisibility(View.VISIBLE);
                        adapter1 = new SearchDateAdapter(mContext, ja, IConstant.INTENT_SUPPLIER_ATTITUDE);
                        lv1.setAdapter(adapter1);
                        adapter2 = new SearchDateAdapter(mContext, ja2, IConstant.INTENT_SUPPLIER_ATTITUDE);
                        adapter2.setIsList1(false);
                        lv2.setAdapter(adapter2);
                        if (current_list == 1) {
                            lv1.setVisibility(View.VISIBLE);
                            lv2.setVisibility(View.GONE);
                        } else {
                            lv1.setVisibility(View.GONE);
                            lv2.setVisibility(View.VISIBLE);
                        }
                        tv_error_info.setVisibility(View.GONE);
                    } else {
                        fl_list.setVisibility(View.GONE);
                        tv_error_info.setVisibility(View.VISIBLE);
                    }

                } catch (JSONException e) {
                    fl_list.setVisibility(View.GONE);
                    tv_error_info.setVisibility(View.VISIBLE);
                    tv_error_info.setText("数据解析出错");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                //Toast.makeText(mContext, ex.getMessage(), Toast.LENGTH_LONG).show();
                //System.out.println("出错：" + ex.getCause().toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });

    }

    public void showPopWindow(TextView parent) {
        if (popupWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = layoutInflater.inflate(R.layout.layout_popwindow, null);
            lv_group = (ListView) view.findViewById(R.id.lvGroup);
            numbers = getResources().getStringArray(R.array.production_percent_state);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    R.layout.item_pop, numbers);
            lv_group.setAdapter(adapter);
            // 创建一个PopuWidow对象
            popupWindow = new PopupWindow(view, 300, LinearLayout.LayoutParams.WRAP_CONTENT);
        }
        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);

        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        int xPos = windowManager.getDefaultDisplay().getWidth() / 2
                - popupWindow.getWidth() / 2;

        popupWindow.showAsDropDown(parent, xPos, 0);

        lv_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                                    int position, long id) {
                tv_state.setText(numbers[position]);
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });
    }

    public void showPopWindow2(TextView parent) {
        if (popupWindow2 == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = layoutInflater.inflate(R.layout.layout_popwindow, null);
            lv_group2 = (ListView) view.findViewById(R.id.lvGroup);
            numbers2 = getResources().getStringArray(R.array.production_percent_date);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    R.layout.item_pop, numbers2);
            lv_group2.setAdapter(adapter);
            // 创建一个PopuWidow对象
            popupWindow2 = new PopupWindow(view, 300, LinearLayout.LayoutParams.WRAP_CONTENT);
        }
        // 使其聚集
        popupWindow2.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow2.setOutsideTouchable(true);

        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow2.setBackgroundDrawable(new BitmapDrawable());
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        int xPos = windowManager.getDefaultDisplay().getWidth() / 2
                - popupWindow2.getWidth() / 2;

        popupWindow2.showAsDropDown(parent, xPos, 0);

        lv_group2.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                                    int position, long id) {
                //tv_quick_seach.setText(numbers2[position]);
                if (popupWindow2 != null) {
                    popupWindow2.dismiss();
                }
            }
        });
    }

}
